<template>
	<view class="Contact-card">
		<form class="form">
			<view class="form-box">
				<view class="title">
					联系人
				</view>
				<view class="form">
					<view class="input">
						<text>姓名</text>
						<input type="text" name="Name" v-model="orderForm.Name" placeholder="请输入姓名"
							placeholder-class="inputstyle" style="width: 80%;" />
					</view>
					<view class="input">
						<text>手机号</text>
						<input type="tel" name="phoneNumber" v-model="orderForm.phoneNumber" placeholder="请输入手机号"
							placeholder-class="inputstyle" style="width: 80%;" />
					</view>
				</view>
			</view>

			<view v-for="(room, index) in rooms" :key="index" class="form-box">
				<view class="title">
					意向房型{{ index + 1 }}
					<text class="cancal" @click="removeRoom(index)">+</text>
				</view>
				<view class="form">
					<view class="input">
						<text>床型</text>
						<view class="Bedtype">
							<view v-for="(item, i) in bedType" class="type-box">
								{{item}}
							</view>
							<view class="tips">
								后期服务可调配
							</view>
						</view>
					</view>
					<view class="input">
						<text>出行人</text>
						<view class="Travelers">
							<view v-if="room.selectedItems.length > 0" class="isTravelers">
								<block v-for="(item, i) in room.selectedItems" :key="i">
									<view class="people-card">
										<view class="lt">
											<view class="info-card">
												<view class="name">{{item.travelers_name}}</view>
												<view class="Idnumber">身份证 {{item.travelers_card_number}}</view>
											</view>
										</view>
										<image src="../../../static/product-cwr/chahao.png"
											@click="removeTraveler(index, item)"></image>
									</view>
								</block>
							</view>
							<view class="Travelers-box" @click="TravelersPopShow(index)">
								<image src="../../../static/product-cwr/jiahao.png" mode=""></image>
								选择出行人
							</view>
						</view>
					</view>
					<view v-if="room.isSingle" class="input">
						<text>独享房间</text>
						需支付单房差
						<text style="color: rgba(99, 29, 29, 1); ">￥{{singleDifferenceRate}}</text>
						<image src="../../../static/product-cwr/duihao.png" mode=""></image>
					</view>
				</view>
			</view>


			<!-- 添加房间按钮 -->
			<view v-if="orderinfo.peoples > rooms.length * 2 && rooms.length < 8" class="form-box  add-box">
			<uni-icons type="plusempty" size="24"></uni-icons>

				<view class="addRoom" @click="addRoom">添加房间</view>
			</view>

			<view class="form-box">
				<view class="title">
					优惠方案
				</view>
				<view class="form">
					<view class="input">
						<text>优惠券</text>
						<text>暂无可用的券</text>
					</view>
				</view>
			</view>

			<!-- 预定按钮 -->
			<view class="expenses-box">
				<button @click="submitForm" class="button">
					立即预定
				</button>
			</view>
		</form>
	</view>

	<TravelersPopVue ref="isTravelersPop" :orderinfo="orderinfo" :roomIndex="index" :idInfo="idInfo" @result="getIdInfo"
		:roomsValue="rooms">
	</TravelersPopVue>
</template>

<script setup>
	import TravelersPopVue from './TravelersPop.vue';
	import {
		ref,
		watch,
		onMounted
	} from 'vue';

	const props = defineProps({
		orderinfo: {
			type: Object,
			default: () => {}
		},
		addPersonInfo: {
			type: Object,
			default: () => {}
		},
		idInfo: {
			type: Array,
			default: () => []
		},
		singleDifferenceRate: {
			type: Number,
			default: 0
		}
	});

	const orderForm = ref({
		phoneNumber: null,
		Name: ''
	});
	const isTravelersPop = ref(null)
	const rooms = ref([]);
	const selectedItems = ref([]);
	const bedType = ref(['大床房', '双床房']);
	const emits = defineEmits(['roomCountChange', 'roomValue', 'submitForm'])
	//监听新增出行人
	watch(() => props.addPersonInfo, (newVal) => {
		props.idInfo.push(newVal);
	});
	//监听房间长度
	watch(() => rooms.value.length, (newVal) => {
		emits('roomCountChange', newVal)
	})
	//监听各个房型里面人数数据
	// watch(() => rooms.value, (newVal) => {
	// 	emits('roomValue', newVal)
	// 	newVal.forEach((room) => {
	// 		room.isSingle = room.selectedItems.length < 2;
	// 	})
	// }, {
	// 	deep: true
	// })
	watch(() => rooms.value, (newVal) => {
		emits('roomValue', newVal)
		newVal.forEach((room, index) => {
			// 检查总出行人数是否为1
			const totalTravelers = newVal.reduce((total, r) => total + r.selectedItems.length, 0);
			if (totalTravelers === 1 && room.selectedItems.length === 1) {
				room.isSingle = false; // 如果整个订单只有一个人，则不视为独享房间
			} else {
				room.isSingle = room.selectedItems.length < 2;
			}
		})
	}, {
		deep: true
	})
	onMounted(() => {
		addDefaultRoom();
	})
	// 添加默认房间的方法
	const addDefaultRoom = () => {
		rooms.value.push({
			peoples: Math.min(2, props.orderinfo.peoples), // 每个房间最多2人
			selectedItems: [], // 初始化为空数组
			isSingle: props.orderinfo.peoples === 1 ? false : undefined // 根据出行人数决定是否标记为独享房间
		});
	};
	const TravelersPopShow = (roomIndex) => {
		isTravelersPop.value.showPopup(roomIndex); // 传递当前房型索引
	};


	const getIdInfo = (value, roomIndex) => {
		console.log('value', value);
		if (value == null) {
			isTravelersPop.value.closePopup();
		} else {
			const idCards = rooms.value.flatMap(room => room.selectedItems.map(item => item.travelers_card_number));
			const filteredValue = value.filter(item => !idCards.includes(item.travelers_card_number));

			if (filteredValue.length > 0) {
				rooms.value[roomIndex].selectedItems = [
					...rooms.value[roomIndex].selectedItems,
					...filteredValue
				];
				console.log('rooms.value===>最终', rooms.value);
			} else {
				console.log('没有新增的出行人');
			}

			isTravelersPop.value.closePopup();
		}

	};

	const addRoom = () => {
		// 计算当前所有房间已添加的出行人数
		const totalTravelers = rooms.value.reduce((total, room) => total + room.selectedItems.length, 0);

		// 检查是否超过可添加的总人数
		if (totalTravelers >= props.orderinfo.peoples) {
			uni.showToast({
				title: `已达到最大出行人数，不能再添加房间`,
				icon: 'none'
			});
			return; // 阻止添加房间
		}

		// 如果人数未满，允许添加房间
		if (rooms.value.length < 8) { // 限制最多只能添加8个房间
			rooms.value.push({
				peoples: Math.min(2, props.orderinfo.peoples - totalTravelers), // 每个房间最多2人，且不超过剩余出行人数
				selectedItems: [], // 初始化为空数组
				isSingle: false // 初始值
			});
		}
	};
	const removeRoom = (index) => {
		rooms.value.splice(index, 1);
	};

	const submitForm = () => {
		// 计算当前已添加的出行人数
		const totalTravelers = rooms.value.reduce((total, room) => total + room.selectedItems.length, 0);
		let resultCode = 0 //0是失败
		//检查是否填写些联系人和电话
		if (orderForm.value.Name == '' || orderForm.value.phoneNumber == '') {
			uni.showToast({
				title: `请填写联系人姓名和电话`,
				icon: 'none'
			});
			resultCode = 0;
			emits('submitForm', resultCode, orderForm.value);
			return;
		}
		// 校验手机号
		const phoneReg = /^1[3-9]\d{9}$/;
		if (!phoneReg.test(orderForm.value.phoneNumber)) {
			uni.showToast({
				title: '请输入有效的手机号',
				icon: 'none',
			});
			resultCode = 0;
			emits('submitForm', resultCode, orderForm.value);
			return;
		}
		// 检查是否满足要求的人数
		if (totalTravelers < props.orderinfo.peoples) {
			const remaining = props.orderinfo.peoples - totalTravelers;
			uni.showToast({
				title: `还需要添加 ${remaining} 位出行人`,
				icon: 'none'
			});
			resultCode = 0;
			emits('submitForm', resultCode, orderForm.value);
			return; // 阻止提交
		}
		resultCode = 1;
		emits('submitForm', resultCode, orderForm.value, rooms.value)
	};

	const removeTraveler = (roomIndex, traveler) => {
		// 获取指定房间的 selectedItems
		const room = rooms.value[roomIndex];

		// 使用 filter 移除指定的 traveler
		room.selectedItems = room.selectedItems.filter(item => item !== traveler);

	};
</script>

<style scoped>
	.Contact-card {
		width: 100%;

	}

	.Contact-card .title {
		display: flex;
		justify-content: space-between;
		font-size: 34rpx;
		font-weight: 400;
	}

	.Contact-card .title text {
		font-weight: lighter;
	}

	.form-box {
		width: 94%;
		margin: 20rpx auto;
		border-radius: 10.76rpx;
		background: rgba(255, 255, 255, 1);
		padding: 16rpx 18rpx;
		box-sizing: border-box;
	}
	.add-box{
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 10rpx;
	}

	.form {
		display: flex;
		flex-direction: column;
		gap: 50rpx;
		margin-top: 20rpx;
	}

	.addRoom {
		/* width: 100%; */
		display: flex;
		justify-content: center;
		padding: 20rpx;
		font-size: 30rpx;
		box-sizing: border-box;
	}

	.input {
		display: flex;
		gap: 35rpx;
		align-items: center;
		color: rgba(56, 56, 56, 1);
		font-size: 24rpx;
		font-weight: 400;
	}

	.input text {
		width: 24%;
		color: rgba(56, 56, 56, 1);
		font-size: 26rpx;
		font-weight: 400;
	}

	.input image {
		width: 20rpx;
		height: 20rpx;
	}

	/deep/.inputstyle {
		font-size: 26rpx;
		font-weight: 400;
		color: rgba(196, 196, 196, 1);
	}

	.expenses-box {
		width: 100%;
		position: fixed;
		/* position: sticky; */
		bottom: 0;
		background-color: rgba(255, 255, 255, 1);
		border-radius: 18rpx;
		padding: 24rpx 24rpx 54rpx 24rpx;
		box-sizing: border-box;
		display: flex;
		gap: 30rpx;
		flex-direction: column;
		z-index: 9;
	}

	.text-box {
		width: 100%;
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.button {
		width: 100%;
		text-align: center;
		opacity: 1;
		color: rgba(255, 255, 255, 1);
		border-radius: 56rpx;
		background: rgba(54, 48, 48, 1);
		box-shadow: 0rpx 4rpx 8rpx rgba(0, 0, 0, 0.25);
		box-sizing: border-box;
	}

	.cancal {
		transform: rotate(45deg);
		font-size: 50rpx;
	}

	.tips {
		font-size: 22rpx;
	}

	.Bedtype {
		width: 100%;
		display: flex;
		gap: 56rpx;
		align-items: center;
	}

	.type-box {
		border: 2rpx solid rgba(125, 125, 125, 1);
		color: rgba(77, 77, 77, 1.0);
		font-size: 26rpx;
		font-weight: 400;
		padding: 8rpx 20rpx;
		box-sizing: border-box;
		transition: all 0.5s;
	}

	.type-box-active {
		border: 2rpx solid rgba(4, 75, 173, 1);
		color: rgba(4, 75, 173, 1);
	}

	.Travelers {
		width: 100%;
		display: flex;
		align-items: center;
		flex-direction: column;
		justify-content: center;
		gap: 20rpx;
	}

	.Travelers-box {
		width: 90%;
		display: flex;
		align-items: center;
		justify-content: center;
		background: rgba(243, 243, 243, 1.0);
		padding: 20rpx;
		border-radius: 28rpx;
		box-sizing: border-box;
		gap: 24rpx;
	}

	.Travelers image {
		width: 32rpx;
		height: 32rpx;
	}

	.Travelers text {
		font-size: 28rpx;
		font-weight: 400;
	}

	.isTravelers {
		width: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		gap: 14rpx;
	}

	.isTravelers .people-card {
		width: 100%;
		background-color: #fff;
		border-radius: 10rpx;
		padding: 28rpx 20rpx;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #eee;
	}

	.people-card image {
		width: 24rpx;
		height: 24rpx;
	}

	.people-card .lt {
		display: flex;
		gap: 20rpx;
		align-items: center;
	}

	.info-card .name {
		font-size: 26rpx;
	}

	.info-card .Idnumber {
		margin-top: 10rpx;
		font-size: 24rpx;
		font-weight: normal;
		color: rgba(125, 125, 125, 1);
	}
</style>